var render = {};
var program;
var scene = {};
var requestId;

function init()
{
    var gl = initWebGL("example");
    if (!gl) {
      return;
    }
    
    vshader = $("<script id='vshader' type='x-shader/x-vertex'></script>");
    vshader.append(defaultVShader);
    $("body").append(vshader);
    
    fshader = $("<script id='fshader' type='x-shader/x-fragment'></script>");
    fshader.append(defaultFShader);
    $("body").append(fshader);
    
    program = simpleSetup(
        gl,
        "vshader", "fshader",
        [ "vNormal", "vPosition"],
        [ 0, 0, 0.5, 1 ], 10000);

    render.mvMatrix = new J3DIMatrix4();
    render.normalMatrix = new J3DIMatrix4();
    render.mvpMatrix = new J3DIMatrix4();

    return gl;
}

function reshape(gl)
{
    var canvas = document.getElementById('example');
    if (canvas.clientWidth == canvas.width && canvas.clientHeight == canvas.height)
        return;

    canvas.width = canvas.clientWidth;
    canvas.height = canvas.clientHeight;

    gl.viewport(0, 0, canvas.clientWidth, canvas.clientHeight);
    render.perspectiveMatrix = new J3DIMatrix4();
    render.perspectiveMatrix.perspective(30, canvas.clientWidth / canvas.clientHeight, 1, 10000);
    render.perspectiveMatrix.lookat(0, 0, 7, 0, 0, 0, 0, 1, 0);
}

function drawPicture(gl)
{
    reshape(gl);
    
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

    render.mvMatrix.makeIdentity();
    render.mvMatrix.rotate(20, 1,0,0);
    render.mvMatrix.rotate(20, 0,1,0);

    render.normalMatrix.load(render.mvMatrix);
    
    render.mvpMatrix.load(render.perspectiveMatrix);
    render.mvpMatrix.multiply(render.mvMatrix);
    
    
    gl.useProgram(program);
    
    gl.uniform3f(gl.getUniformLocation(program, "lightDir"), 0, 0, 1);
    render.normalMatrix.setUniform(gl, gl.getUniformLocation(program, "u_normalMatrix"), false);
    render.mvpMatrix.setUniform(gl, gl.getUniformLocation(program, "u_modelViewProjMatrix"), false);
    
    gl.enableVertexAttribArray(0);
    gl.enableVertexAttribArray(1); 
    
    for(index in scene.elements){
    	element = scene.elements[index];
        gl.bindBuffer(gl.ARRAY_BUFFER, element.vertexObject);
        gl.vertexAttribPointer(1, 3, gl.FLOAT, false, 0, 0);

        gl.bindBuffer(gl.ARRAY_BUFFER, element.normalObject);
        gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 0, 0);
        
        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, element.indexObject);
        
        gl.drawElements(gl.TRIANGLES, element.numIndices, gl.UNSIGNED_BYTE, 0);
    }

}

function start()
{
	var gl = init();
    if (!gl) {
       return;
    }
	
    initScene();
    
    var c = document.getElementById("example");

    var f = function() {
        drawPicture(gl);
        requestId = window.requestAnimFrame(f, c);
    };
    f();

}